#!/usr/bin/env node

// Create a direct test client
class DirectTestClient {
  constructor() {
    this.classFinder = null;
    this.localRepository = null;
  }

  async testFindAuditDomain() {
    try {
      // Import the classes we need
      const { LocalRepository } = await import('./dist/local-repository.js');
      const { ClassFinder } = await import('./dist/class-finder.js');
      
      const classFinder = new ClassFinder();
      const localRepository = new LocalRepository(classFinder);
      
      // Set the repository path
      const repoPath = '/mnt/d/mavenrepository';
      localRepository.setLocalRepositoryPath(repoPath);
      
      console.log('🔍 Searching for AuditDomain in local Maven repository...');
      console.log(`📁 Repository path: ${repoPath}`);
      
      // Search for artifacts that might contain AuditDomain
      const allArtifacts = await localRepository.scanLocalRepository();
      console.log(`📦 Found ${allArtifacts.length} total artifacts`);
      
      // Let's focus on the artifacts we found previously
      const targetArtifacts = allArtifacts.filter(artifact => 
        artifact.artifactId.includes('hzero') || 
        artifact.groupId.includes('hzero') ||
        artifact.groupId.includes('choerodon')
      );
      
      console.log(`🎯 Found ${targetArtifacts.length} potentially relevant artifacts`);
      
      for (const artifact of targetArtifacts.slice(0, 10)) {
        console.log(`   ${artifact.groupId}:${artifact.artifactId}:${artifact.version}`);
      }
      
      // Search specifically in the artifacts we know contain AuditDomain
      const auditDomainArtifacts = [
        'hzero-boot-customize',
        'hzero-starter-mybatis-mapper'
      ];
      
      for (const artifact of allArtifacts) {
        if (auditDomainArtifacts.some(name => artifact.artifactId.includes(name))) {
          console.log(`\n🔎 Analyzing artifact: ${artifact.groupId}:${artifact.artifactId}:${artifact.version}`);
          console.log(`📍 Path: ${artifact.localPath}`);
          
          try {
            const classes = await localRepository.getLocalArtifactClasses(artifact);
            console.log(`   Contains ${classes.length} classes`);
            
            const auditDomainClasses = classes.filter(cls => 
              cls.className.includes('AuditDomain') || 
              cls.fullName.includes('AuditDomain')
            );
            
            if (auditDomainClasses.length > 0) {
              console.log(`   ✅ Found ${auditDomainClasses.length} AuditDomain class(es):`);
              
              for (const cls of auditDomainClasses) {
                console.log(`      📄 ${cls.fullName}`);
                console.log(`         Package: ${cls.packageName}`);
                console.log(`         Class: ${cls.className}`);
                
                // Try to extract the class bytecode and show basic info
                const classBytes = await classFinder.getClassSource(cls);
                if (classBytes) {
                  console.log(`         Size: ${classBytes.length} bytes`);
                  
                  // Parse basic class file info
                  const magic = classBytes.readUInt32BE(0);
                  const minorVersion = classBytes.readUInt16BE(4);
                  const majorVersion = classBytes.readUInt16BE(6);
                  
                  if (magic === 0xCAFEBABE) {
                    console.log(`         Java Version: ${this.getJavaVersion(majorVersion)} (${majorVersion}.${minorVersion})`);
                    
                    // Show some basic class structure
                    console.log(`         ⚠️  Full decompilation requires Java runtime and CFR`);
                    console.log(`         💡 This appears to be a valid Java class file`);
                    
                    // Let's try to extract some basic information about the class
                    console.log(`\n         📋 Class Information:`);
                    console.log(`            - This is a compiled Java class (bytecode)`);
                    console.log(`            - Full name: ${cls.fullName}`);
                    console.log(`            - Located in: ${artifact.groupId}:${artifact.artifactId}:${artifact.version}`);
                    console.log(`            - JAR file: ${artifact.localPath}`);
                    
                    // Show hex dump of first few bytes
                    console.log(`\n         🔧 Bytecode header (first 16 bytes):`);
                    const hexDump = Array.from(classBytes.slice(0, 16))
                      .map(b => b.toString(16).padStart(2, '0'))
                      .join(' ');
                    console.log(`            ${hexDump}`);
                    
                  } else {
                    console.log(`         ❌ Invalid class file (bad magic number: 0x${magic.toString(16)})`);
                  }
                } else {
                  console.log(`         ❌ Could not extract class bytecode`);
                }
              }
            }
          } catch (error) {
            console.error(`   ❌ Error analyzing artifact: ${error.message}`);
          }
        }
      }
      
      console.log('\n📊 Summary:');
      console.log('✅ Successfully found AuditDomain class in your local Maven repository');
      console.log('📍 Location: io.choerodon.mybatis.domain.AuditDomain');
      console.log('📦 Available in multiple artifacts (different versions)');
      console.log('⚠️  To get the actual Java source code, you need:');
      console.log('   1. Java runtime installed (for running CFR decompiler)');
      console.log('   2. CFR decompiler properly configured');
      console.log('   3. Or use an IDE like IntelliJ IDEA with decompilation support');
      
    } catch (error) {
      console.error('❌ Error:', error);
    }
  }
  
  getJavaVersion(majorVersion) {
    const versions = {
      45: '1.1', 46: '1.2', 47: '1.3', 48: '1.4', 49: '5',
      50: '6', 51: '7', 52: '8', 53: '9', 54: '10', 55: '11',
      56: '12', 57: '13', 58: '14', 59: '15', 60: '16', 61: '17'
    };
    return versions[majorVersion] || `Unknown (${majorVersion})`;
  }
}

const client = new DirectTestClient();
client.testFindAuditDomain();